import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;

/**
 * This is the compiler!!
 * Put the pipes together 
 * @author MLB
 *
 */
class VslComp {
	public static void main(String[] args) {
		int option = 0;
	    if( args.length != 2) {
	    	System.err.println("USAGE VSLComp fichier.vsl option \n where option is -mips or -vsm");
	    	System.exit(1);
	    };
	    if ( args[1].equals("-mips")) option = 0;
	    else
	    	if ( args[1].equals("-vsm")) option = 1;
	    	else {
	    		System.err.println("USAGE VSLComp fichier.vsl option \n where option is -mips or -vsm");
	    		System.err.println("Unknown option - give up");
	    		System.exit(1);
	    	};

	    
		try {
			
		    ANTLRFileStream input = new ANTLRFileStream(args[0]);
		    //ANTLRInputStream input = new ANTLRInputStream(System.in);
			VSLLexer lexer = new VSLLexer(input);
			CommonTokenStream token_stream = new CommonTokenStream(lexer);
			VSLParser parser = new VSLParser(token_stream);
			
			// Parse the input expression
			VSLParser.program_return r = parser.program();

	        //resulting tree
	        CommonTree t = (CommonTree)r.getTree();
		
	        // Print the resulting tree out in LISP notation
	        //System.out.println(t.toStringTree());
			
	        CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
	        VSLTreeParser tparser = new VSLTreeParser(nodes);
			 try {
				  Code3a code = tparser.program();
				  //System.out.println("affichage code 3 adresses :");
				  //code.print();
				  if (option == 1){
					VSMCodeGenerator cg = new VSMCodeGenerator(System.out);
					cg.genCode(code);
					 }
				  else {
				  	MIPSCodeGenerator cg = new MIPSCodeGenerator(System.out);
				  	cg.genCode(code);}
				  
			 }
			catch (Exception e) {
				System.err.println(e.getMessage());
				e.printStackTrace();
			}
			
		}
		catch (FileNotFoundException fnf){
			    System.err.println("exception: "+fnf);
		}
		
		catch (RecognitionException re){
			System.err.println("Recognition exception: "+re);
		}

		catch (IOException exc) {
			// TODO Auto-generated catch block
			//exc.printStackTrace();
			System.out.println("IO exception");
		}
	}
	
}
